import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import layout from '@/views/layout'
import myorder from '@/views/myOrder'
import pay from '@/views/pay'
import predetail from '@/views/predetail'
import search from '@/views/search'
import searchlist from '@/views/searchList'
import cart from '@/views/layout/cart.vue'
import home from '@/views/layout/home.vue'
import layout1 from '@/views/layout/layout.vue'
import user from '@/views/layout/user.vue'
import store from '@/store'
import { Toast } from 'vant'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: login, name: 'Login' },
    {
      path: '/',
      component: layout,
      redirect: '/home',
      children: [
        { path: '/cart', component: cart },
        { path: '/home', component: home },
        { path: '/user', component: user },
        { path: '/layout1', component: layout1 }
      ]
    },
    { path: '/myorder', component: myorder },
    { path: '/pay', component: pay },
    { path: '/predetail/:id', component: predetail },
    { path: '/search', component: search },
    { path: '/searchlist', component: searchlist }
  ]
})
const authUrl = ['/pay', '/myorder']
const token = store.state.user.userInfo
router.beforeEach((to, from, next) => {
  if (!authUrl.includes(to.path)) {
    next()
    return
  }

  if (token) {
    next()
    Toast('登录令牌成功')
  } else {
    next({ path: '/login' })
    Toast('错误')
  }
})

// router.beforeEach((to, from, next) => {
//   if (to.name !== 'Login' && store.state.user.userInfo === null) {
//     next({ name: 'Login' })
//     Toast('错误')
//   } else next()
// })

export default router
